package cn.edu.lingnan.filter;


import cn.edu.lingnan.controller.Result;
import cn.edu.lingnan.utils.JwtUtils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@Component
public class LoginCheckInterceptor implements HandlerInterceptor {

//    @Override
//    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        String url = request.getRequestURL().toString();
//        log.info("请求 URL: {}", url);
//
//
//        if (url.contains("login")||url.contains("register") || url.contains("verify") || url.contains("captcha")) {
//            log.info("这是一个登录请求");
//            return true;
//        }
//
//        String jwt = request.getHeader("Authorization");
//        log.info("Token: {}", jwt);
//        if (jwt != null && jwt.startsWith("Bearer ")) {
//            jwt = jwt.substring(7); // 移除 "Bearer "前缀
//        }
//
//        if (!StringUtils.hasLength(jwt)) {
//            log.info("令牌为空");
//            response.setContentType("application/json");
//            response.setCharacterEncoding("UTF-8");
//            Result error = Result.unauthorized("没有登录");
//            String notLogin = JSONObject.toJSONString(error);
//            response.getWriter().write(notLogin);
//            return false;
//        }
//
//        // 解析令牌
//        try {
//            JwtUtils.parseJWT(jwt);
//        } catch (Exception e) {
//            log.error("无法解析令牌", e);
//            response.setContentType("application/json");
//            response.setCharacterEncoding("UTF-8");
//            Result error = Result.unauthorized("令牌无效");
//            String notLogin = JSONObject.toJSONString(error);
//            response.getWriter().write(notLogin);
//            return false;
//        }
//
//        log.info("令牌有效");
//        return true;
//    }
//
//    @Override
//    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//    }
//
//    @Override
//    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        // This can be used for cleanup after the request has been completed
//    }
}
